/*
 * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include "sdmmc_common.h"

sdmmc_err_t sdmmc_send_cmd(sdmmc_card_t* card, sdmmc_command_t* cmd)
{
    if (card->host.command_timeout_ms != 0) {
        cmd->timeout_ms = card->host.command_timeout_ms;
    } else if (cmd->timeout_ms == 0) {
        cmd->timeout_ms = SDMMC_DEFAULT_CMD_TIMEOUT_MS;
    }

    int slot = card->host.slot;
    // SDMMC_LOGV("sending cmd slot=%d op=%"PRIu32" arg=%"PRIu32" flags=%x data=%p "
    //            "blklen=%"PRIuPTR" datalen=%"PRIuPTR" timeout=%"PRIu32"\n", slot, cmd->opcode,
    //            cmd->arg, cmd->flags, cmd->data, cmd->blklen, cmd->datalen, cmd->timeout_ms);
    sdmmc_err_t err = (*card->host.do_transaction)(slot, cmd);
    if (err != 0) {
        SDMMC_LOGD("cmd=%"PRIu32", sdmmc_req_run returned 0x%x", cmd->opcode, err);
        return err;
    }
    // int state = MMC_R1_CURRENT_STATE(cmd->response);
    // SDMMC_LOGV("cmd response %08"PRIx32" %08"PRIx32" %08"PRIx32" %08"PRIx32" err=0x%x state=%d\n",
    //            cmd->response[0], cmd->response[1], cmd->response[2], cmd->response[3], cmd->error, state);
    return cmd->error;
}

sdmmc_err_t sdmmc_send_app_cmd(sdmmc_card_t* card, sdmmc_command_t* cmd)
{
    sdmmc_command_t app_cmd = {
        .opcode = MMC_APP_CMD,
        .flags = SCF_CMD_AC | SCF_RSP_R1,
        .arg = MMC_ARG_RCA(card->rca),
    };
    sdmmc_err_t err = sdmmc_send_cmd(card, &app_cmd);
    if (err != SDMMC_OK) {
        return err;
    }
    // Check APP_CMD status bit (only in SD mode)
    if (!host_is_spi(card) && !(MMC_R1(app_cmd.response) & MMC_R1_APP_CMD)) {
        SDMMC_LOGW("card doesn't support APP_CMD\n");
        return SDMMC_ERR_NOT_SUPPORTED;
    }
    return sdmmc_send_cmd(card, cmd);
}


sdmmc_err_t sdmmc_send_cmd_go_idle_state(sdmmc_card_t* card)
{
    sdmmc_command_t cmd = {
        .opcode = MMC_GO_IDLE_STATE,
        .flags = SCF_CMD_BC | SCF_RSP_R0,
    };
    sdmmc_err_t err = sdmmc_send_cmd(card, &cmd);
    if (host_is_spi(card)) {
        /*
         * 要进入SPI模式, CMD0需要发送两次(参见SD简化规范v4.10中的图4-1).
         * 有些卡在第一个CMD0时进入SD模式, 所以不要期望上面的命令成功.
         * 下面的SCF_RSP_R1标志告诉下层期望正确的R1响应(在SPI模式下).
         */
        (void) err;
        sdmmc_sys_delay_ms(SDMMC_GO_IDLE_DELAY_MS);

        cmd.flags |= SCF_RSP_R1;
        err = sdmmc_send_cmd(card, &cmd);
    }
    if (err == SDMMC_OK) {
        sdmmc_sys_delay_ms(SDMMC_GO_IDLE_DELAY_MS);
    }
    return err;
}


sdmmc_err_t sdmmc_send_cmd_send_if_cond(sdmmc_card_t* card, uint32_t ocr)
{
    const uint8_t pattern = 0xaa; /* any pattern will do here */
    sdmmc_command_t cmd = {
        .opcode = SD_SEND_IF_COND,
        .arg = (((ocr & SD_OCR_VOL_MASK) != 0) << 8) | pattern,
        .flags = SCF_CMD_BCR | SCF_RSP_R7,
    };
    sdmmc_err_t err = sdmmc_send_cmd(card, &cmd);
    if (err != SDMMC_OK) {
        return err;
    }
    uint8_t response = cmd.response[0] & 0xff;
    if (response != pattern) {
        SDMMC_LOGE("%s: received=0x%x expected=0x%x\n", __func__, response, pattern);
        return SDMMC_ERR_INVALID_RESPONSE;
    }
    return SDMMC_OK;
}

sdmmc_err_t sdmmc_send_cmd_send_op_cond(sdmmc_card_t* card, uint32_t ocr, uint32_t *ocrp)
{
    sdmmc_err_t err;

    sdmmc_command_t cmd = {
            .arg = ocr,
            .flags = SCF_CMD_BCR | SCF_RSP_R3,
            .opcode = SD_APP_OP_COND
    };
    int nretries = SDMMC_SEND_OP_COND_MAX_RETRIES;
    int err_cnt = SDMMC_SEND_OP_COND_MAX_ERRORS;
    for (; nretries != 0; --nretries)  {
        bzero(&cmd, sizeof cmd);
        cmd.arg = ocr;
        cmd.flags = SCF_CMD_BCR | SCF_RSP_R3;
        if (!card->is_mmc) { /* SD mode */
            cmd.opcode = SD_APP_OP_COND;
            err = sdmmc_send_app_cmd(card, &cmd);
        } else { /* MMC mode */
            cmd.arg &= ~MMC_OCR_ACCESS_MODE_MASK;
            cmd.arg |= MMC_OCR_SECTOR_MODE;
            cmd.opcode = MMC_SEND_OP_COND;
            err = sdmmc_send_cmd(card, &cmd);
        }

        if (err != SDMMC_OK) {
            if (--err_cnt == 0) {
                SDMMC_LOGD("%s: sdmmc_send_app_cmd err=0x%x\n", __func__, err);
                return err;
            } else {
                SDMMC_LOGV("%s: ignoring err=0x%x\n", __func__, err);
                continue;
            }
        }
        /*
         * 在SD协议中, 当准备就绪时, OCR.MEM_READY位被置位.
         * 在SPI协议中, 当准备就绪时, R1响应中的IDLE_STATE位被清零.
         */
        if (!host_is_spi(card)) {
            if ((MMC_R3(cmd.response) & MMC_OCR_MEM_READY) || ocr == 0) {
                break;
            }
        } else {
            if ((SD_SPI_R1(cmd.response) & SD_SPI_R1_IDLE_STATE) == 0) {
                break;
            }
        }
        sdmmc_sys_delay_ms(10);
    }
    if (nretries == 0) {
        return SDMMC_ERR_TIMEOUT;
    }
    if (ocrp) {
        *ocrp = MMC_R3(cmd.response);
    }
    return SDMMC_OK;
}

sdmmc_err_t sdmmc_send_cmd_read_ocr(sdmmc_card_t *card, uint32_t *ocrp)
{
    SDMMC_ASSERT(ocrp);
    sdmmc_command_t cmd = {
        .opcode = SD_READ_OCR,
        .flags = SCF_CMD_BCR | SCF_RSP_R2
    };
    sdmmc_err_t err = sdmmc_send_cmd(card, &cmd);
    if (err != SDMMC_OK) {
        return err;
    }
    *ocrp = SD_SPI_R3(cmd.response);
    return SDMMC_OK;
}


sdmmc_err_t sdmmc_send_cmd_all_send_cid(sdmmc_card_t* card, sdmmc_response_t* out_raw_cid)
{
    SDMMC_ASSERT(out_raw_cid);
    sdmmc_command_t cmd = {
            .opcode = MMC_ALL_SEND_CID,
            .flags = SCF_CMD_BCR | SCF_RSP_R2
    };
    sdmmc_err_t err = sdmmc_send_cmd(card, &cmd);
    if (err != SDMMC_OK) {
        return err;
    }
    memcpy(out_raw_cid, &cmd.response, sizeof(sdmmc_response_t));
    return SDMMC_OK;
}

sdmmc_err_t sdmmc_send_cmd_send_cid(sdmmc_card_t *card, sdmmc_cid_t *out_cid)
{
    SDMMC_ASSERT(out_cid);
    SDMMC_ASSERT(host_is_spi(card) && "SEND_CID should only be used in SPI mode");
    SDMMC_ASSERT(!card->is_mmc && "MMC cards are not supported in SPI mode");
    sdmmc_response_t buf;
    sdmmc_command_t cmd = {
        .opcode = MMC_SEND_CID,
        .flags = SCF_CMD_READ | SCF_CMD_ADTC,
        .arg = 0,
        .data = &buf[0],
        .datalen = sizeof(buf)
    };
    sdmmc_err_t err = sdmmc_send_cmd(card, &cmd);
    if (err != SDMMC_OK) {
        return err;
    }
    sdmmc_flip_byte_order(buf, sizeof(buf));
    return sdmmc_decode_cid(buf, out_cid);
}


sdmmc_err_t sdmmc_send_cmd_set_relative_addr(sdmmc_card_t* card, uint16_t* out_rca)
{
    SDMMC_ASSERT(out_rca);
    sdmmc_command_t cmd = {
            .opcode = SD_SEND_RELATIVE_ADDR,
            .flags = SCF_CMD_BCR | SCF_RSP_R6
    };

    /* MMC卡期望我们设置RCA. 将RCA设置为1，因为目前我们不支持同一总线上的多张卡. */
    uint16_t mmc_rca = 1;
    if (card->is_mmc) {
        cmd.arg = MMC_ARG_RCA(mmc_rca);
    }

    sdmmc_err_t err = sdmmc_send_cmd(card, &cmd);
    if (err != SDMMC_OK) {
        return err;
    }
    *out_rca = (card->is_mmc) ? mmc_rca : SD_R6_RCA(cmd.response);
    return SDMMC_OK;
}

sdmmc_err_t sdmmc_send_cmd_set_blocklen(sdmmc_card_t* card, sdmmc_csd_t* csd)
{
    sdmmc_command_t cmd = {
            .opcode = MMC_SET_BLOCKLEN,
            .arg = csd->sector_size,
            .flags = SCF_CMD_AC | SCF_RSP_R1
    };
    return sdmmc_send_cmd(card, &cmd);
}

sdmmc_err_t sdmmc_send_cmd_send_csd(sdmmc_card_t* card, sdmmc_csd_t* out_csd)
{
    /*
     * SEND_CSD的诀窍在于, 在SPI模式下, 它作为一个数据读取命令.
     * 而在SD模式下，它是一个具有R2响应的AC命令.
     */
    sdmmc_response_t spi_buf;
    const bool is_spi = host_is_spi(card);
    sdmmc_command_t cmd = {
            .opcode = MMC_SEND_CSD,
            .arg = is_spi ? 0 : MMC_ARG_RCA(card->rca),
            .flags = is_spi ? (SCF_CMD_READ | SCF_CMD_ADTC | SCF_RSP_R1) :
                    (SCF_CMD_AC | SCF_RSP_R2),
            .data = is_spi ? &spi_buf[0] : 0,
            .datalen = is_spi ? sizeof(spi_buf) : 0,
    };
    sdmmc_err_t err = sdmmc_send_cmd(card, &cmd);
    if (err != SDMMC_OK) {
        return err;
    }
    uint32_t* ptr = cmd.response;
    if (is_spi) {
        sdmmc_flip_byte_order(spi_buf,  sizeof(spi_buf));
        ptr = spi_buf;
    }
    if (card->is_mmc) {
        err = sdmmc_mmc_decode_csd(cmd.response, out_csd);
    } else {
        err = sdmmc_decode_csd(ptr, out_csd);
    }
    return err;
}

sdmmc_err_t sdmmc_send_cmd_select_card(sdmmc_card_t* card, uint32_t rca)
{
    /* 不要期望在取消选择卡片时看到响应. */
    uint32_t response = (rca == 0) ? 0 : SCF_RSP_R1;
    sdmmc_command_t cmd = {
            .opcode = MMC_SELECT_CARD,
            .arg = MMC_ARG_RCA(rca),
            .flags = SCF_CMD_AC | response
    };
    return sdmmc_send_cmd(card, &cmd);
}

sdmmc_err_t sdmmc_send_cmd_send_scr(sdmmc_card_t* card, sdmmc_scr_t *out_scr)
{
    size_t datalen = 8;
    uint32_t* buf = (uint32_t*) sdmmc_sys_heap_caps_malloc(512, MALLOC_CAP_DMA);
    if (buf == NULL) {
        return SDMMC_ERR_NO_MEM;
    }
    sdmmc_command_t cmd = {
            .data = buf,
            .datalen = datalen,
            .blklen = datalen,
            .flags = SCF_CMD_ADTC | SCF_CMD_READ | SCF_RSP_R1,
            .opcode = SD_APP_SEND_SCR
    };
    sdmmc_err_t err = sdmmc_send_app_cmd(card, &cmd);
    if (err == SDMMC_OK) {
        err = sdmmc_decode_scr(buf, out_scr);
    }
    sdmmc_sys_free(buf);
    return err;
}

sdmmc_err_t sdmmc_send_cmd_set_bus_width(sdmmc_card_t* card, int width)
{
    sdmmc_command_t cmd = {
            .opcode = SD_APP_SET_BUS_WIDTH,
            .flags = SCF_RSP_R1 | SCF_CMD_AC,
            .arg = (width == 4) ? SD_ARG_BUS_WIDTH_4 : SD_ARG_BUS_WIDTH_1,
    };

    return sdmmc_send_app_cmd(card, &cmd);
}

sdmmc_err_t sdmmc_send_cmd_crc_on_off(sdmmc_card_t* card, bool crc_enable)
{
    SDMMC_ASSERT(host_is_spi(card) && "CRC_ON_OFF can only be used in SPI mode");
    sdmmc_command_t cmd = {
            .opcode = SD_CRC_ON_OFF,
            .arg = crc_enable ? 1 : 0,
            .flags = SCF_CMD_AC | SCF_RSP_R1
    };
    return sdmmc_send_cmd(card, &cmd);
}

sdmmc_err_t sdmmc_send_cmd_send_status(sdmmc_card_t* card, uint32_t* out_status)
{
    sdmmc_command_t cmd = {
            .opcode = MMC_SEND_STATUS,
            .arg = MMC_ARG_RCA(card->rca),
            .flags = SCF_CMD_AC | SCF_RSP_R1
    };
    sdmmc_err_t err = sdmmc_send_cmd(card, &cmd);
    if (err != SDMMC_OK) {
        return err;
    }
    if (out_status) {
        if (host_is_spi(card)) {
            *out_status = SD_SPI_R2(cmd.response);
        } else {
            *out_status = MMC_R1(cmd.response);
        }
    }
    return SDMMC_OK;
}

sdmmc_err_t sdmmc_write_sectors(sdmmc_card_t* card, const void* src,
        size_t start_block, size_t block_count)
{
    sdmmc_err_t err = SDMMC_OK;
    size_t block_size = card->csd.sector_size;

    if (SDMMC_PTR_DMA_CAP(src)){
        err = sdmmc_write_sectors_dma(card, src, start_block, block_count);
    } else {
        // SDMMC peripheral needs DMA-capable buffers. Split the write into
        // separate single block writes, if needed, and allocate a temporary
        // DMA-capable buffer.
        void* tmp_buf = sdmmc_sys_heap_caps_malloc(block_size * block_count, MALLOC_CAP_DMA);
        if (tmp_buf == NULL) {
            return SDMMC_ERR_NO_MEM;
        }

        memcpy(tmp_buf, src, block_size * block_count);
        err = sdmmc_write_sectors_dma(card, tmp_buf, start_block, block_count);
        if (err != SDMMC_OK) {
            SDMMC_LOGE("%s: error 0x%x writing block %"PRIuPTR"+%"PRIuPTR"\n", __func__, err, start_block, block_count);
        }

        sdmmc_sys_free(tmp_buf);
    }

    return err;
}

sdmmc_err_t sdmmc_write_sectors_dma(sdmmc_card_t* card, const void* src,
        size_t start_block, size_t block_count)
{
    if (start_block + block_count > (size_t)card->csd.capacity) {
        return SDMMC_ERR_INVALID_SIZE;
    }
    size_t block_size = card->csd.sector_size;
    sdmmc_command_t cmd = {
            .flags = SCF_CMD_ADTC | SCF_RSP_R1,
            .blklen = block_size,
            .data = (void*) src,
            .datalen = block_count * block_size,
            .timeout_ms = SDMMC_WRITE_CMD_TIMEOUT_MS
    };
    if (block_count == 1) {
        cmd.opcode = MMC_WRITE_BLOCK_SINGLE;
    } else {
        cmd.opcode = MMC_WRITE_BLOCK_MULTIPLE;
    }
    if (card->ocr & SD_OCR_SDHC_CAP) {
        cmd.arg = start_block;
    } else {
        cmd.arg = start_block * block_size;
    }
    sdmmc_err_t err = sdmmc_send_cmd(card, &cmd);
    if (err != SDMMC_OK) {
        SDMMC_LOGE("%s: sdmmc_send_cmd returned 0x%x\n", __func__, err);
        return err;
    }
    uint32_t status = 0;
    size_t count = 0;
    /* SD mode: wait for the card to become idle based on R1 status */
    while (!host_is_spi(card) && !(status & MMC_R1_READY_FOR_DATA)) {
        // TODO: add some timeout here
        err = sdmmc_send_cmd_send_status(card, &status);
        if (err != SDMMC_OK) {
            return err;
        }
        if (++count % 10 == 0) {
            SDMMC_LOGV("waiting for card to become ready (%"PRIuPTR")\n", count);
        }
    }
    /* SPI mode: although card busy indication is based on the busy token,
     * SD spec recommends that the host checks the results of programming by sending
     * SEND_STATUS command. Some of the conditions reported in SEND_STATUS are not
     * reported via a data error token.
     */
    if (host_is_spi(card)) {
        err = sdmmc_send_cmd_send_status(card, &status);
        if (err != SDMMC_OK) {
            return err;
        }
        if (status & SD_SPI_R2_CARD_LOCKED) {
            SDMMC_LOGE("%s: write failed, card is locked: r2=0x%04"PRIx32"\n", __func__, status);
            return SDMMC_ERR_INVALID_STATE;
        }
        if (status != 0) {
            SDMMC_LOGE("%s: card status indicates an error after write operation: r2=0x%04"PRIx32"\n", __func__, status);
            return SDMMC_ERR_INVALID_RESPONSE;
        }
    }
    return SDMMC_OK;
}

sdmmc_err_t sdmmc_read_sectors(sdmmc_card_t* card, void* dst,
        size_t start_block, size_t block_count)
{
    sdmmc_err_t err = SDMMC_OK;
    size_t block_size = card->csd.sector_size;

    if (SDMMC_PTR_DMA_CAP(dst)){
        err = sdmmc_read_sectors_dma(card, dst, start_block, block_count);
    } else {
        // SDMMC peripheral needs DMA-capable buffers. Split the read into
        // separate single block reads, if needed, and allocate a temporary
        // DMA-capable buffer.
        void* tmp_buf = sdmmc_sys_heap_caps_malloc(block_size * block_count, MALLOC_CAP_DMA);
        if (tmp_buf == NULL) {
            return SDMMC_ERR_NO_MEM;
        }

        err = sdmmc_read_sectors_dma(card, tmp_buf, start_block, block_count);
        if (err != SDMMC_OK) {
            SDMMC_LOGE("%s: error 0x%x writing block %"PRIuPTR"+%"PRIuPTR"\n", __func__, err, start_block, block_count);
        } else {
            memcpy(dst, tmp_buf, block_size * block_count);
        }

        sdmmc_sys_free(tmp_buf);
    }

    return err;
}

sdmmc_err_t sdmmc_read_sectors_dma(sdmmc_card_t* card, void* dst,
        size_t start_block, size_t block_count)
{
    if (start_block + block_count > (size_t)card->csd.capacity) {
        return SDMMC_ERR_INVALID_SIZE;
    }
    size_t block_size = card->csd.sector_size;
    sdmmc_command_t cmd = {
            .flags = SCF_CMD_ADTC | SCF_CMD_READ | SCF_RSP_R1,
            .blklen = block_size,
            .data = (void*) dst,
            .datalen = block_count * block_size
    };
    if (block_count == 1) {
        cmd.opcode = MMC_READ_BLOCK_SINGLE;
    } else {
        cmd.opcode = MMC_READ_BLOCK_MULTIPLE;
    }
    if (card->ocr & SD_OCR_SDHC_CAP) {
        cmd.arg = start_block;
    } else {
        cmd.arg = start_block * block_size;
    }
    sdmmc_err_t err = sdmmc_send_cmd(card, &cmd);
    if (err != SDMMC_OK) {
        SDMMC_LOGE("%s: sdmmc_send_cmd returned 0x%x\n", __func__, err);
        return err;
    }
    uint32_t status = 0;
    size_t count = 0;
    while (!host_is_spi(card) && !(status & MMC_R1_READY_FOR_DATA) &&
           !(SD_R1_CURRENT_STATE(status) == MMC_R1_CURRENT_STATE_TRAN)) {
        err = sdmmc_send_cmd_send_status(card, &status);
        if (err != SDMMC_OK) {
            return err;
        }
        if (++count % 10 == 0) {
            SDMMC_LOGD("waiting for card to become ready (%"PRIuPTR")\n", count);
        }
        sdmmc_sys_delay_ms(1U);
    }

    SDMMC_LOGD("last card status = %"PRIu32"\n", SD_R1_CURRENT_STATE(status));
    return SDMMC_OK;
}

sdmmc_err_t sdmmc_erase_sectors(sdmmc_card_t* card, size_t start_sector,
        size_t sector_count, sdmmc_erase_arg_t arg)
{
    if (start_sector + sector_count > (size_t)card->csd.capacity) {
        return SDMMC_ERR_INVALID_SIZE;
    }

    uint32_t cmd38_arg;
    if (arg == SDMMC_ERASE_ARG) {
        cmd38_arg = card->is_mmc ? SDMMC_MMC_TRIM_ARG : SDMMC_SD_ERASE_ARG;
    } else {
        cmd38_arg = card->is_mmc ? SDMMC_MMC_DISCARD_ARG : SDMMC_SD_DISCARD_ARG;
    }

    /* validate the CMD38 argument against card supported features */
    if (card->is_mmc) {
        if ((cmd38_arg == SDMMC_MMC_TRIM_ARG) && (sdmmc_can_trim(card) != SDMMC_OK)) {
            return SDMMC_ERR_NOT_SUPPORTED;
        }
        if ((cmd38_arg == SDMMC_MMC_DISCARD_ARG) && (sdmmc_can_discard(card) != SDMMC_OK)) {
            return SDMMC_ERR_NOT_SUPPORTED;
        }
    } else { // SD card
        if ((cmd38_arg == SDMMC_SD_DISCARD_ARG) && (sdmmc_can_discard(card) != SDMMC_OK)) {
            return SDMMC_ERR_NOT_SUPPORTED;
        }
    }

    /* default as block unit address */
    size_t addr_unit_mult = 1;

    if (!(card->ocr & SD_OCR_SDHC_CAP)) {
        addr_unit_mult = card->csd.sector_size;
    }

    /* prepare command to set the start address */
    sdmmc_command_t cmd = {
            .flags = SCF_CMD_AC | SCF_RSP_R1 | SCF_WAIT_BUSY,
            .opcode = card->is_mmc ? MMC_ERASE_GROUP_START :
                    SD_ERASE_GROUP_START,
            .arg = (start_sector * addr_unit_mult),
    };

    sdmmc_err_t err = sdmmc_send_cmd(card, &cmd);
    if (err != SDMMC_OK) {
        SDMMC_LOGE("%s: sdmmc_send_cmd (ERASE_GROUP_START) returned 0x%x\n", __func__, err);
        return err;
    }

    /* prepare command to set the end address */
    cmd.opcode = card->is_mmc ? MMC_ERASE_GROUP_END : SD_ERASE_GROUP_END;
    cmd.arg = ((start_sector + (sector_count - 1)) * addr_unit_mult);

    err = sdmmc_send_cmd(card, &cmd);
    if (err != SDMMC_OK) {
        SDMMC_LOGE("%s: sdmmc_send_cmd (ERASE_GROUP_END) returned 0x%x\n", __func__, err);
        return err;
    }

    /* issue erase command */
    memset((void *)&cmd, 0 , sizeof(sdmmc_command_t));
    cmd.flags = SCF_CMD_AC | SCF_RSP_R1B | SCF_WAIT_BUSY;
    cmd.opcode = MMC_ERASE;
    cmd.arg = cmd38_arg;
    cmd.timeout_ms = sdmmc_get_erase_timeout_ms(card, cmd38_arg, sector_count * card->csd.sector_size / 1024);

    err = sdmmc_send_cmd(card, &cmd);
    if (err != SDMMC_OK) {
        SDMMC_LOGE("%s: sdmmc_send_cmd (ERASE) returned 0x%x\n", __func__, err);
        return err;
    }

    if (host_is_spi(card)) {
        uint32_t status;
        err = sdmmc_send_cmd_send_status(card, &status);
        if (err != SDMMC_OK) {
            return err;
        }
        if (status != 0) {
            SDMMC_LOGE("%s: card status indicates an error after erase operation: r2=0x%04"PRIx32"\n", __func__, status);
            return SDMMC_ERR_INVALID_RESPONSE;
        }
    }

    return SDMMC_OK;
}

sdmmc_err_t sdmmc_can_discard(sdmmc_card_t* card)
{
    if ((card->is_mmc) && (card->ext_csd.rev >= EXT_CSD_REV_1_6)) {
         return SDMMC_OK;
    }
    // SD card
    if ((!card->is_mmc) && !host_is_spi(card) && (card->ssr.discard_support == 1)) {
        return SDMMC_OK;
    }
    return SDMMC_FAIL;
}

sdmmc_err_t sdmmc_can_trim(sdmmc_card_t* card)
{
    if ((card->is_mmc) && (card->ext_csd.sec_feature & EXT_CSD_SEC_GB_CL_EN)) {
        return SDMMC_OK;
    }
    return SDMMC_FAIL;
}

sdmmc_err_t sdmmc_mmc_can_sanitize(sdmmc_card_t* card)
{
    if ((card->is_mmc) && (card->ext_csd.sec_feature & EXT_CSD_SEC_SANITIZE)) {
        return SDMMC_OK;
    }
    return SDMMC_FAIL;
}

sdmmc_err_t sdmmc_mmc_sanitize(sdmmc_card_t* card, uint32_t timeout_ms)
{
    sdmmc_err_t err;
    uint8_t index = EXT_CSD_SANITIZE_START;
    uint8_t set = EXT_CSD_CMD_SET_NORMAL;
    uint8_t value = 0x01;

    if (sdmmc_mmc_can_sanitize(card) != SDMMC_OK) {
        return SDMMC_ERR_NOT_SUPPORTED;
    }
    /*
     * A Sanitize operation is initiated by writing a value to the extended
     * CSD[165] SANITIZE_START. While the device is performing the sanitize
     * operation, the busy line is asserted.
     * SWITCH command is used to write the EXT_CSD register.
     */
    sdmmc_command_t cmd = {
            .opcode = MMC_SWITCH,
            .arg = (MMC_SWITCH_MODE_WRITE_BYTE << 24) | (index << 16) | (value << 8) | set,
            .flags = SCF_RSP_R1B | SCF_CMD_AC | SCF_WAIT_BUSY,
            .timeout_ms = timeout_ms,
    };
    err = sdmmc_send_cmd(card, &cmd);
    if (err == SDMMC_OK) {
        //check response bit to see that switch was accepted
        if (MMC_R1(cmd.response) & MMC_R1_SWITCH_ERROR) {
            err = SDMMC_ERR_INVALID_RESPONSE;
        }
    }
    return err;
}

sdmmc_err_t sdmmc_full_erase(sdmmc_card_t* card)
{
    sdmmc_erase_arg_t arg = SDMMC_SD_ERASE_ARG; // erase by default for SD card
    sdmmc_err_t err;
    if (card->is_mmc) {
        arg = sdmmc_mmc_can_sanitize(card) == SDMMC_OK ? SDMMC_MMC_DISCARD_ARG: SDMMC_MMC_TRIM_ARG;
    }
    err = sdmmc_erase_sectors(card, 0, card->csd.capacity, arg);
    if ((err == SDMMC_OK) && (arg == SDMMC_MMC_DISCARD_ARG)) {
        uint32_t timeout_ms = sdmmc_get_erase_timeout_ms(card, SDMMC_MMC_DISCARD_ARG, card->csd.capacity * ((uint64_t) card->csd.sector_size) / 1024);
        return sdmmc_mmc_sanitize(card, timeout_ms);
    }
    return err;
}

sdmmc_err_t sdmmc_get_status(sdmmc_card_t* card)
{
    uint32_t stat;
    return sdmmc_send_cmd_send_status(card, &stat);
}
